﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TicketSeller
{
    class TicketsFinderService : ITicketsFinderService
    {
        public TicketsCollection search( string source, string destination, string date) {
            var tickets = (from t in TicketsDB.Instance.getTicketsCopy()
                           where t.date == date && t.source == source && t.destination == destination
                           select t).ToList( );
            foreach (string serverName in ClusterManager.Instance.HasReplicationOf)
            {
                // Aggregate all replicated data
                var tmp = ( from t in TicketsDB.Instance.getTicketsByServerName( serverName)
                            where t.date == date && t.source == source && t.destination == destination
                            select t).ToList( );

                foreach (var x in tmp)
                    tickets.Add(x);
            }
            return new TicketsCollection( tickets);
        }

        // Select all flights which starts at source on given date.
        public TicketsCollection searchFrom( string source, string date) {
            var tickets = (from t in TicketsDB.Instance.getTicketsCopy()
                           where t.date == date && t.source == source
                           select t).ToList();

            foreach( string serverName in ClusterManager.Instance.HasReplicationOf) {
                foreach (var x in (from t in TicketsDB.Instance.getTicketsByServerName(serverName)
                                   where t.date.Equals(date) && t.source.Equals(source)
                                   select t).ToList())
                    tickets.Add(x);
            }
            return new TicketsCollection( tickets);
        }

        // Select all flights wich endpoint is destination.
        public TicketsCollection searchTo( string destination, string date) {
            var tickets = (from t in TicketsDB.Instance.getTicketsCopy()
                           where t.date.Equals( date) && t.destination.Equals( destination)
                           select t).ToList();

            foreach (string serverName in ClusterManager.Instance.HasReplicationOf)
            {
                foreach( var x in ( ( from t in TicketsDB.Instance.getTicketsByServerName( serverName)
                                      where t.date.Equals( date) && t.destination.Equals( destination)
                                      select t).ToList( )))
                                      tickets.Add( x);
            }
            return new TicketsCollection( tickets);
        }
    }
}
